import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";

// 创建axios实例
const service = axios.create({
	baseURL: "http://localhost:3000/api", // API基础URL
	timeout: 10000, // 请求超时时间
	headers: {
		"Content-Type": "application/json;charset=utf-8",
	},
});

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		// 在发送请求之前做些什么
		if (store.getters.token) {
			config.headers["Authorization"] = `Bearer ${store.getters.token}`;
		}
		return config;
	},
	(error) => {
		console.error("请求错误:", error);
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response) => {
		const res = response.data;

		// 如果返回的状态码不是200，说明接口有问题，把错误信息显示出来
		if (res.code !== 200) {
			Message({
				message: res.message || "系统错误",
				type: "error",
				duration: 5 * 1000,
			});

			// 401: 未登录或token过期
			if (res.code === 401) {
				// 重新登录
				store.dispatch("user/resetToken").then(() => {
					location.reload();
				});
			}

			return Promise.reject(new Error(res.message || "系统错误"));
		} else {
			return res;
		}
	},
	(error) => {
		console.error("响应错误:", error);
		Message({
			message: error.message || "系统错误",
			type: "error",
			duration: 5 * 1000,
		});
		return Promise.reject(error);
	}
);

// 统一处理请求方法
const http = {
	get(url, params) {
		return service.get(url, { params });
	},
	post(url, data) {
		return service.post(url, data);
	},
	put(url, data) {
		return service.put(url, data);
	},
	patch(url, data) {
		return service.patch(url, data);
	},
	delete(url, params) {
		return service.delete(url, { params });
	},
};

export default http;
